package com.efounder.form.comp.multiple_images_selector;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager.widget.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.efounder.imageloader.GlideImageLoader;
import com.efounder.mobilecomps.R;

import java.util.ArrayList;
import java.util.List;

/**
 * 这个是用于进行图片浏览时的界面
 *
 * @author king
 * @version 2014年10月18日  下午11:47:53
 * @QQ:595163260
 */
public class GalleryActivity extends Activity {
    private Intent intent;
    //删除按钮
    private Button del_bt;
    //顶部显示预览图片位置的textview
    private TextView positionTextView;
    //获取前一个activity传过来的position
    private int position;
    //当前的位置
    private int location = 0;
    String imageUrl;

    private ArrayList<String> listViews = null;
    private ViewPager pager;
    private MyPageAdapter adapter;


    public ArrayList<String> del = new ArrayList<String>();

    private Context mContext;
    private ImageView btn_backpress;

    private static List<ImageSelectorRecycleListener> imageSelectorRecycleListeners = new
            ArrayList<>();

    RelativeLayout photo_relativeLayout;

//    ImageLoader imageLoader = ImageLoader.getInstance();
//    DisplayImageOptions options;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.plugin_camera_gallery);// 切屏到主界面
        mContext = this;

        del_bt = (Button) findViewById(R.id.gallery_del);
        del_bt.setOnClickListener(new DelListener());
        intent = getIntent();
        Bundle bundle = intent.getExtras();
        //yqs屏蔽 单一预览
        //  del = intent.getStringArrayListExtra("urllist");
        position = intent.getIntExtra("ID", 0);
        imageUrl = intent.getStringExtra("url");
        del.add(imageUrl);


        btn_backpress = (ImageView) findViewById(R.id.btn_backpress);
        btn_backpress.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                GalleryActivity.this.finish();
            }
        });

        // 为发送按钮设置文字
        pager = (ViewPager) findViewById(R.id.gallery01);
        pager.setOnPageChangeListener(pageChangeListener);
//		for (int i = 0; i < Bimp.tempSelectBitmap.size(); i++) {
//			initListViews( Bimp.tempSelectBitmap.get(i).getBitmap() );
//		}
//        for (int i = 0; i < del.size(); i++) {
//            String urlNeedEdit = del.get(i);
//			String url ="";
//			if(urlNeedEdit.contains("file://")) {
//				url = urlNeedEdit.substring(7);
//			}else{
//				url = urlNeedEdit;
//			}
//
//            BitmapFactory.Options options = new BitmapFactory.Options();
//
//            options.inPreferredConfig = Bitmap.Config.ARGB_4444;
//
//            Bitmap img = BitmapFactory.decodeFile(url,options);
//            initListViews(img);
//        }
//        imageLoader.init(ImageLoaderConfiguration.createDefault(mContext));
//
//        options = new DisplayImageOptions.Builder()
//                .showImageOnLoading(R.drawable.ic_launcher) //设置图片在下载期间显示的图片
//                .showImageForEmptyUri(R.drawable.ic_launcher)//设置图片Uri为空或是错误的时候显示的图片
//                .showImageOnFail(R.drawable.ic_launcher)  //设置图片加载/解码过程中错误时候显示的图片
//                .cacheInMemory(true)//设置下载的图片是否缓存在内存中
//                .cacheOnDisc(true)//设置下载的图片是否缓存在SD卡中
//                .considerExifParams(true)  //是否考虑JPEG图像EXIF参数（旋转，翻转）
//                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//设置图片以如何的编码方式显示
//                .bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型//
////                .decodingOptions(android.graphics.BitmapFactory.Options)//设置图片的解码配置
////.delayBeforeLoading(int delayInMillis)//int delayInMillis为你设置的下载前的延迟时间
////设置图片加入缓存前，对bitmap进行设置
////.preProcessor(BitmapProcessor preProcessor)
//                .resetViewBeforeLoading(true)//设置图片在下载前是否重置，复位
//                .displayer(new RoundedBitmapDisplayer(20))//是否设置为圆角，弧度为多少
//                .displayer(new FadeInBitmapDisplayer(100))//是否图片加载好后渐入的动画时间
//                .build();//构建完成

        adapter = new MyPageAdapter(del);
        pager.setAdapter(adapter);
        pager.setPageMargin(getResources().getDimensionPixelOffset(R.dimen.ui_10_dip));
        pager.setCurrentItem(position);
    }

    private OnPageChangeListener pageChangeListener = new OnPageChangeListener() {

        public void onPageSelected(int arg0) {
            location = arg0;
        }

        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }

        public void onPageScrollStateChanged(int arg0) {

        }
    };

//	private void initListViews(Bitmap bm) {
//		if (listViews == null)
//			listViews = new ArrayList<View>();
//		PhotoView img = new PhotoView(this);
//		//img.setBackgroundColor(0xff000000);
//		img.setImageBitmap(bm);
//		img.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
//				LayoutParams.MATCH_PARENT));
//		listViews.add(img);
//	}


    // 删除按钮添加的监听器
    private class DelListener implements OnClickListener {

        public void onClick(View v) {
            if (del.size() > 0) {
                Intent intent = new Intent();
                intent.putExtra("pos",position);
                setResult(1,intent);
                if (del.size() == 1) {

                    for (ImageSelectorRecycleListener imageSelectorRecycleListener :
                            imageSelectorRecycleListeners) {
                        imageSelectorRecycleListener.removePosition(position);
                    }
                    finish();
                } else {
                    for (ImageSelectorRecycleListener imageSelectorRecycleListener :
                            imageSelectorRecycleListeners) {
                        imageSelectorRecycleListener.removePosition(position);
                    }
                    position--;
                    pager.removeAllViews();
                    del.remove(location);
                    adapter.setImageurllists(del);
                    adapter.notifyDataSetChanged();
                }
            } else {
                GalleryActivity.this.finish();
            }
        }
    }


    class MyPageAdapter extends PagerAdapter {

        private ArrayList<String> imageurllists;
        private ArrayList<ImageView> listImageViews;

        private int size;

        public MyPageAdapter(ArrayList<String> _imageurllists) {
            this.imageurllists = _imageurllists;
            listImageViews = new ArrayList<ImageView>();
            for (int i = 0; i < imageurllists.size(); i++) {
                ImageView imageView = new ImageView(GalleryActivity.this);
                LinearLayout.LayoutParams imageViewParam = new LinearLayout.LayoutParams
                        (ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                imageView.setLayoutParams(imageViewParam);
                listImageViews.add(imageView);
                GlideImageLoader.getInstance().displayImage(mContext,imageView,imageurllists.get(i));
//                imageLoader.displayImage(imageurllists.get(i), imageView);
            }
            size = imageurllists == null ? 0 : imageurllists.size();
        }

        public void setImageurllists(ArrayList<String> _imageurllists) {
            this.imageurllists = _imageurllists;
            for (int i = 0; i < imageurllists.size(); i++) {
                ImageView imageView = new ImageView(GalleryActivity.this);
                LinearLayout.LayoutParams imageViewParam = new LinearLayout.LayoutParams
                        (ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                imageView.setLayoutParams(imageViewParam);
                listImageViews.add(imageView);
                GlideImageLoader.getInstance().displayImage(mContext,imageView,imageurllists.get(i));
//                imageLoader.displayImage(imageurllists.get(i), imageView);
            }
            size = imageurllists == null ? 0 : imageurllists.size();
        }

        public int getCount() {
            return size;
        }

        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        public void destroyItem(View arg0, int arg1, Object arg2) {
            ((ViewPager) arg0).removeView(listImageViews.get(arg1 % size));
        }

        public void finishUpdate(View arg0) {
        }

        public Object instantiateItem(View arg0, int arg1) {
            try {
                ((ViewPager) arg0).addView(listImageViews.get(arg1 % size), 0);

            } catch (Exception e) {
            }
            return listImageViews.get(arg1 % size);
        }

        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

    }

    public interface ImageSelectorRecycleListener {

        //返回网络状态的类型  0：无网络，tcp掉线  1：登录成功
        void removePosition(int position);

    }

    // 添加观察者  edit by lc
    public static void addImageSelectorRecycleListener(ImageSelectorRecycleListener
                                                               imageSelectorRecycleListener) {
        if (!imageSelectorRecycleListeners.contains(imageSelectorRecycleListener)) {
            imageSelectorRecycleListeners.add(imageSelectorRecycleListener);
        }
    }

    //移除观察者
    public void removeAllImageSelectorRecycleListener() {
        imageSelectorRecycleListeners.clear();
    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        removeAllImageSelectorRecycleListener();
    }
}
